package com.dayuanit.dy16.atm.handler;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;

/**
 * 负责发送邮件
 */
@Component
public class EmailHandler {

    @Value("${atm.host}")
    private String host;

    @Value("${email.reset.password.url}")
    private String resetPwdUrl;

    @Value("${email.active.url}")
    private String activeUrl;

    @Value("${email.deadline.second}")
    private int timeout;

    public EmailHandler() {
        System.out.println("EmailHandler()");
    }

    @Autowired
    private JavaMailSenderImpl javaMailSender;

    @Value("${atm.password.salt}")
    private String passwordSalt;

    public void sendResetPassword(String toEamil) {
        long endTime = System.currentTimeMillis() + (1000 * timeout);
        String sign = DigestUtils.md5Hex(toEamil + passwordSalt + endTime);

        StringBuilder sx = new StringBuilder();
        sx.append(host).append(resetPwdUrl).append("?")
                .append("email=").append(toEamil).append("&")
                .append("sign=").append(sign).append("&")
                .append("endTime=").append(endTime);

        sendEmail(toEamil, sx.toString() + " 重置密码", "ATM系统重置密码");
    }

    /**
     * 发送激活的邮件
     * @param toEmail
     * @param userId
     */
    public void sendActiveEmail(String toEmail, long userId) {
        long endTime = System.currentTimeMillis() + (1000 * timeout);
        String sign = DigestUtils.md5Hex(toEmail + userId + passwordSalt + endTime);

        StringBuilder sx = new StringBuilder();
        sx.append(host).append(activeUrl).append("?")
                .append("email=").append(toEmail).append("&")
                .append("userId=").append(userId).append("&")
                .append("sign=").append(sign).append("&")
                .append("endTime=").append(endTime);

        sendEmail(toEmail, "", "atm系统激活邮箱");
    }


    private void sendEmail(String toEmail, String text, String subject) {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message);

        try {
            helper.setFrom("dayuanitatm@163.com");
            helper.setTo(toEmail);
            helper.setSubject(subject);
            helper.setText(text);
            javaMailSender.send(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
